//
// Created by Administrator on 2021/11/20.
//

#include "Transform.h"

const Mat4x4f& Transform::localToWorldMatrix()
{
    if(m_l2wDirty)
    {
        m_l2wDirty = false;
        // TR(RzRxRy)S三矩阵相乘
        // 可以直接写
        // RzRxRy矩阵
        float r = m_rotation.z() * Deg2Rad;
        float p = m_rotation.x() * Deg2Rad;
        float h = m_rotation.y() * Deg2Rad;
        float sx = m_scale.x();
        float sy = m_scale.y();
        float sz = m_scale.z();
        float tx = m_position.x();
        float ty = m_position.y();
        float tz = m_position.z();
        m_localToWorldMatrix = Mat4x4f(
                sx * (cosf(r) * cosf(h) - sinf(r) * sinf(p) * sinf(h)), -sinf(r) * cosf(p),       cosf(r) * sinf(h) + sinf(r) * sinf(p) * cosf(h), tx,
                sinf(r) * cosf(h) + cosf(r) * sinf(p) * sinf(h),        sy * (cosf(r) * cosf(p)), sinf(r) * sinf(h) - cosf(r) * sinf(p) * cosf(h), ty,
                -cosf(p) * sinf(h),                                          sinf(p),                  sz * (cosf(p) * cosf(h)),                        tz,
                0.0f,                                                   0.0f,                     0.0f,                                       1.0f);

    }

    return m_localToWorldMatrix;
}

Vec3f Transform::forward()
{
    Mat4x4f matrix = localToWorldMatrix();
    Vec3f vec = Vec3f(matrix[0][2], matrix[1][2], matrix[2][2]);
    vec.Normalize();
    return vec;
}

Vec3f Transform::up()
{
    Mat4x4f matrix = localToWorldMatrix();
    Vec3f vec = Vec3f(matrix[0][1], matrix[1][1], matrix[2][1]);
    vec.Normalize();
    return vec;
}

Vec3f Transform::right()
{
    Mat4x4f matrix = localToWorldMatrix();
    Vec3f vec = Vec3f(matrix[0][0], matrix[1][0], matrix[2][0]);
    vec.Normalize();
    return vec;
}